import { useModel } from "@umijs/max"
import { App, Button, Card, Modal, Row, Slider } from "antd"
import React, { useEffect, useState } from "react"
import { Image, Layer, Stage } from "react-konva"

// 切线图组件
const CutLineImage: React.FC<{ imageData: string | null }> = ({ imageData }) => {
  const [image, setImage] = useState<HTMLImageElement | null>(null)

  React.useEffect(() => {
    if (imageData) {
      const img = new window.Image()
      img.src = `data:image/jpeg;base64,${imageData}`
      img.onload = () => {
        setImage(img)
      }
    } else {
      setImage(null)
    }
  }, [imageData])

  return (
    <Image
      image={image}
      width={image ? image.width : 660}
      height={image ? image.height : 660}
    />
  )
}

const CutLineCheckModal: React.FC = () => {
  const { callPy } = useModel("websocketModel")
  const {
    cutLineModalVisible,
    cutLineImageData,
    calcResInfo,
    workingOrder,
    updateProduceData
  } = useModel("produceModel")
  const { message } = App.useApp()

  // 从 workingOrder 中获取初始留边宽度
  const [firstEdge, setFirstEdge] = useState(workingOrder?.firstEdge ?? 0)
  const [secondEdge, setSecondEdge] = useState(workingOrder?.secondEdge ?? 0)
  const [thirdEdge, setThirdEdge] = useState(workingOrder?.thirdEdge ?? 0)
  const [fourthEdge, setFourthEdge] = useState(workingOrder?.fourthEdge ?? 0)

  useEffect(() => {
    if (workingOrder) {
      setFirstEdge(workingOrder.firstEdge)
      setSecondEdge(workingOrder.secondEdge)
      setThirdEdge(workingOrder.thirdEdge)
      setFourthEdge(workingOrder.fourthEdge)
    }
  }, [workingOrder])

  const [isReturned, setIsReturned] = useState(true)

  const closeModal = () => {
    updateProduceData({
      cutLineModalVisible: false,
      cutLineImageData: null,
      calcResInfo: "",
      isReturned: false
    })
  }

  const handleAfterEdgeChange = async () => {
    const args = [firstEdge, secondEdge, thirdEdge, fourthEdge]
    const response = await callPy("produce", "after_edge_change_from_web", args)
    updateProduceData({ isReturned: true })
    if (!response.state) {
      message.error("留边宽度调整失败:" + response.info, 5)
    }
  }

  const handleCutBoard = async () => {
    closeModal()
    const args = [firstEdge, secondEdge, thirdEdge, fourthEdge]
    const response = await callPy("produce", "cut_board_from_web", args)
    if (response.state) {
      message.success("切板指令下发成功")
    } else {
      message.error("切板指令下发失败:" + response.info, 5)
    }
  }

  const handleBoardBack = async () => {
    const response = await callPy("produce", "board_back_from_web", [])
    if (response.state) {
      message.success("板回退指令下发成功")
    } else {
      message.error("板回退指令下发失败:" + response.info, 5)
    }
  }

  const handleReGetImage = async () => {
    const response = await callPy("produce", "re_get_image_from_web", [])
    if (response.state) {
      closeModal()
    } else {
      message.error(response.info, 5)
    }
  }

  const handleStopProduce = async () => {
    const response = await callPy("produce", "stop_produce_from_web", [])
    if (response.state) {
      message.success("停止自动作业指令下发成功")
      closeModal()
    } else {
      message.error("停止自动作业指令下发失败:" + response.info, 5)
    }
  }

  const handleReHandLabel = async () => {
    closeModal()
    const response = await callPy("produce", "re_hand_label_from_web", [])
    if (!response.state) {
      message.error("重新标注失败:" + response.info, 5)
    }
  }

  return (
    <Modal
      title={
        <span style={{ color: "orange", fontSize: 16, fontWeight: "bold" }}>
          切线图调整确认框
        </span>
      }
      open={cutLineModalVisible}
      width="90vw"
      style={{ top: 5 }}
      footer={null}
      closable={false}
    >
      <Card>
        <Card.Grid style={{ width: "70%", textAlign: "left" }}>
          <Stage width={600} height={600}>
            <Layer>
              <CutLineImage imageData={cutLineImageData} />
            </Layer>
          </Stage>
        </Card.Grid>
        <Card.Grid style={{ width: "30%", textAlign: "left" }}>
          <div style={{ marginTop: 100 }}>
            <div style={{ marginLeft: 16, marginRight: 16 }}>
              第一刀留边宽度
              <Slider
                disabled={!isReturned}
                value={firstEdge}
                max={45}
                min={0}
                onChange={(value: number) => {
                  setFirstEdge(value)
                }}
                onChangeComplete={handleAfterEdgeChange}
              />
            </div>
            <div style={{ marginLeft: 16, marginRight: 16 }}>
              第二刀留边宽度
              <Slider
                disabled={!isReturned}
                value={secondEdge}
                max={45}
                min={0}
                onChange={(value: number) => {
                  setSecondEdge(value)
                }}
                onChangeComplete={handleAfterEdgeChange}
              />
            </div>
            <div style={{ marginLeft: 16, marginRight: 16 }}>
              第三刀留边宽度
              <Slider
                disabled={!isReturned}
                value={thirdEdge}
                max={45}
                min={0}
                onChange={(value: number) => {
                  setThirdEdge(value)
                }}
                onChangeComplete={handleAfterEdgeChange}
              />
            </div>
            <div style={{ marginLeft: 16, marginRight: 16 }}>
              第四刀留边宽度
              <Slider
                disabled={!isReturned}
                value={fourthEdge}
                max={45}
                min={0}
                onChange={(value: number) => {
                  setFourthEdge(value)
                }}
                onChangeComplete={handleAfterEdgeChange}
              />
            </div>
          </div>

          <Row style={{ marginTop: 20 }}>
            <div style={{ marginLeft: 16 }}>
              <span style={{ color: "#0000FF", fontSize: 16 }}>
                识别信息:&nbsp;&nbsp;
              </span>
              <span>{calcResInfo}</span>
            </div>
          </Row>

          <Row style={{ marginTop: 20, marginLeft: 16 }}>
            <Button type="primary" onClick={handleCutBoard}>
              切板
            </Button>
            <Button type="primary" onClick={handleBoardBack} style={{ marginLeft: 20 }}>
              板回退
            </Button>
            <Button type="primary" onClick={handleReGetImage} style={{ marginLeft: 20 }}>
              重新拍照
            </Button>
          </Row>
          <Row style={{ marginTop: 20, marginLeft: 16 }}>
            <Button type="primary" onClick={handleStopProduce}>
              停止
            </Button>
            <Button type="primary" onClick={handleReHandLabel} style={{ marginLeft: 20 }}>
              重新标注
            </Button>
          </Row>
        </Card.Grid>
      </Card>
    </Modal>
  )
}

export default () => (
  <App>
    <CutLineCheckModal />
  </App>
)
